package ferp.center.server.backend;

import ferp.center.server.Action;
import ferp.center.server.entity.Report;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * User: olegs
 * Date: 11/21/12 4:44 PM
 */
public class GameReportDelete extends HttpServlet
{
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    // create inactive profile deletion task
    Action.queueTaskForBackend(response, "delete old reports", "/game/report/delete");
  }

  @SuppressWarnings("unchecked")
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    Action.execute(request, response, Void.class, new Action.Read<Void, Void>()
    {
      public Void run(EntityManager em, Void input) throws IOException
      {
        Query q = em.createQuery("SELECT r FROM Report r WHERE r.created < ?1");

        q.setParameter(1, new Date(System.currentTimeMillis() - MAX_MONTHS_IN_MS));
        q.setMaxResults(CHUNK_SIZE);

        List<Report> reports = q.getResultList();

        for (Report r : reports)
          em.remove(r);

        log("old reports deleted: " + reports.size());

        return null;
      }
    });
  }

  // 2 months old reports
  private static final long MAX_MONTHS = 2;

  private static final long MAX_MONTHS_IN_MS = MAX_MONTHS * 30 * 24 * 60 * 60 * 1000L;
  private static final int CHUNK_SIZE = 5000;
}
